package com.cunshe.config.interceptor;

import com.auth0.jwt.JWT;
import com.cunshe.common.ResponseVO;
import com.cunshe.common.WebConsts;
import com.cunshe.config.annotation.Login;
import com.cunshe.domain.User;
import com.google.gson.Gson;
import org.apache.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 登陆拦截器
 * @author xiao
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> clazz = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();
            Login annotation = clazz.getAnnotation(Login.class);
            if (annotation == null) {
                annotation = method.getAnnotation(Login.class);
            }
            if (annotation != null) {
                User user = null;
                try {
                    String token = request.getHeader("token");
                    String json = JWT.decode(token).getClaim("user").asString();
                    user = new Gson().fromJson(json, User.class);
                } catch (Exception e) {

                }
                if (user == null) {
                    response.setContentType("application/json; charset=utf-8");
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    response.getWriter().println(new Gson().toJson(ResponseVO.error(HttpStatus.SC_UNAUTHORIZED, "登录已过期")));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
